//
//  LoginViewController.m
//  DailyGram
//
//  Created by TiOluwa Olarewaju on 9/1/12.
//  Copyright (c) 2012 MT. All rights reserved.
//

#import "LoginViewController.h"
#import <Parse/Parse.h>

@interface LoginViewController ()

@end

@implementation LoginViewController
@synthesize username;
@synthesize password;

@synthesize delegate;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
}

- (void)viewDidUnload
{
    [self setUsername:nil];
    [self setPassword:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    if (textField == username) {
        [username resignFirstResponder];
    }
    if (textField == password) {
        [password resignFirstResponder];
    }

    
    return NO;
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
    if ([PFUser currentUser]) { // If there is a user logged in from signup, dismiss the modal view
         [self dismissModalViewControllerAnimated:YES];
    }
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if ([segue.identifier isEqualToString:@"signUp"])
	{
        
        
	}
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (IBAction)loginUser:(id)sender {
    [self loginWithUsername:username.text andPassword:password.text];
}

-(void)loginWithUsername:(NSString*)user andPassword:(NSString*)pass{
    [PFUser logInWithUsernameInBackground:user password:pass block:^(PFUser *user, NSError *error) {
        if (user) {
            NSLog(@"Username: %@", [PFUser currentUser]);
            [delegate didLogin:self];
            [self dismissModalViewControllerAnimated:YES];
            
        } else {
            NSLog(@"Login Error: %@", error);
            if (error.code == 101){
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Failure"
                                                                message:@"Incorrect username or password"
                                                               delegate:nil
                                                      cancelButtonTitle:@"OK"
                                                      otherButtonTitles: nil];
                [alert show];
            }
        }
    }];
}

- (IBAction)signUpUser:(id)sender {
   
}

- (IBAction)forgotPassword:(id)sender {
}
@end
